import { EditableFormInstance, ModalForm, PageHeaderWrapper, ProCard, ProCardTabsProps, ProColumns, ProTable } from "@ant-design/pro-components"
import { Children, ReactText, useEffect, useRef, useState } from 'react';
import { Button, Select, Tag, message } from 'antd';
import ProList from '@ant-design/pro-list';
import { PlusOutlined } from '@ant-design/icons';
import UploadFileSave from '@/components/UploadExcelSave';
import { addEncoderConfig, delEncoderConfig, getEncoderConfigByPage, updateEncoderConfig, uploadEncoderExcel } from "@/services/drivepara/encoderConfig";
import EncoderContent from "@/components/DriveParaCalc/EncoderContent";
import EncoderCommon from "@/components/DriveParaCalc/EncoderCommon";
import G120Content from "@/components/DriveParaCalc/G120Content";

const EncoderConfigLib: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<ReactText[]>([]);
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: ReactText[]) => setSelectedRowKeys(keys),
  };
  const [visible, setVisible] = useState(false);
  const driveRef = useRef(null);
  const [values, setValues] = useState({});
  const [encoderCreate, setEncoderCreate] = useState<Boolean>(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);
  const [uploadVis, setUploadVis] = useState(false);
  const uploadRef = useRef(null);
  const formData = new FormData();

  const encoderTypeMap = new Map([
    ['3001', '1024HTL A/B R'],
    ['3005', '1024HTL A/B'],
    ['9999', 'User-defined'],
  ]);

  const encoderColumns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
      align: 'center',
    },
    {
      title: '编码器厂家',
      search: false,
      dataIndex: 'encoderManufacturer',
      width: 60,
      align: 'center',
    },
    {
      title: '编码器类型',
      width: 80,
      search: false,
      align: 'center',
      key: 'encoderType',
      dataIndex: 'encoderType',
      valueType: 'select',
      valueEnum: {
        '3001': {
          text: '1024HTL A/B R',
          status: 'Default',
        },
        '3005': {
          text: '1024HTL A/B',
          status: 'success',
        },
        '9999': {
          text: 'User-defined',
          status: 'error',
        },
      },
    },
    {
      title: '编码器型号',
      search: false,
      dataIndex: 'encoderNum',
      width: 60,
      align: 'center',
    },
    {
      title: '线性编码器 P404[1].00',
      width: 80,
      search: false,
      align: 'center',
      key: 'isLinearEncoder',
      dataIndex: 'isLinearEncoder',
      valueType: 'select',
      valueEnum: {
        0: { text: 'Rotary', status: 'Default', },
        1: { text: 'Linear', status: 'success', },
      },
    },
    {
      title: '绝对值编码器 P404[1].01',
      width: 80,
      search: false,
      align: 'center',
      key: 'isAbsEncoder',
      dataIndex: 'isAbsEncoder',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Default', },
        1: { text: '是', status: 'success', },
      },
    },
    {
      title: '多圈绝对值编码器 P404[1].02',
      width: 80,
      search: false,
      align: 'center',
      key: 'isMultiAbsEncoder',
      dataIndex: 'isMultiAbsEncoder',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Default', },
        1: { text: '是', status: 'success', },
      },
    },
    {
      title: 'SSI编码器 P404[1].09',
      width: 80,
      search: false,
      align: 'center',
      key: 'isSsiEncoder',
      dataIndex: 'isSsiEncoder',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Default', },
        1: { text: '是', status: 'success', },
      },
    },
    {
      title: '电压级24V P404[1].20/P404[1].21',
      width: 80,
      search: false,
      align: 'center',
      key: 'voltageLevel',
      dataIndex: 'voltageLevel',
      valueType: 'select',
      valueEnum: {
        0: { text: '5V', status: 'Default', },
        1: { text: '13.5-30V', status: 'success', },
      },
    },
    {
      title: '遥感仅对SMC30 P404[1].22',
      width: 80,
      search: false,
      align: 'center',
      key: 'remoteSense',
      dataIndex: 'remoteSense',
      valueType: 'select',
      valueEnum: {
        0: { text: 'Unselect', status: 'Default', },
        1: { text: 'Select', status: 'success', },
      },
    },
    {
      title: '信号 P405[0].00',
      width: 80,
      search: false,
      align: 'center',
      key: 'signal',
      dataIndex: 'signal',
      valueType: 'select',
      valueEnum: {
        0: { text: 'Unipolar', status: 'Default', },
        1: { text: 'Bipolar', status: 'success', },
      },
    },
    {
      title: '电平 P405[0].01',
      width: 80,
      search: false,
      align: 'center',
      key: 'level',
      dataIndex: 'level',
      valueType: 'select',
      valueEnum: {
        0: { text: 'HTL', status: 'Default', },
        1: { text: 'TTL', status: 'success', },
      },
    },
    {
      title: '编码器精Gx_XIST1 P418[1]',
      search: false,
      dataIndex: 'gxXist1',
      width: 60,
      align: 'center',
    },
    {
      title: '编码器精Gx_XIST2 P419[1]',
      search: false,
      dataIndex: 'gxXist2',
      width: 60,
      align: 'center',
    },
    {
      title: '绝对值编码器单圈 P423[1]/P408[1]',
      search: false,
      dataIndex: 'singleCircleRes',
      width: 60,
      align: 'center',
    },
    {
      title: '绝对值编码器多圈 P421[1]',
      search: false,
      dataIndex: 'multiCircleRes',
      width: 60,
      align: 'center',
    },

    {
      title: '传输代码 P429[1].00',
      width: 80,
      search: false,
      align: 'center',
      key: 'transCode',
      dataIndex: 'transCode',
      valueType: 'select',
      valueEnum: {
        0: { text: '格雷码', status: 'Default', },
        1: { text: '二进制代码', status: 'success', },
      },
    },
    {
      title: '分辨率 P407[1]',
      search: false,
      dataIndex: 'resolution',
      width: 60,
      align: 'center',
    },
    {
      title: '编码器绝对值位 P447[1]',
      search: false,
      dataIndex: 'ssiAbs',
      width: 60,
      align: 'center',
    },
    {
      title: '编码器之前的位 P446[1]',
      search: false,
      dataIndex: 'ssiBefore',
      width: 60,
      align: 'center',
    },
    {
      title: '编码器之后的位 P448[1]',
      search: false,
      dataIndex: 'ssiAfter',
      width: 60,
      align: 'center',
    },
    {
      title: '波特率 P427[1]',
      search: false,
      dataIndex: 'baudRate',
      width: 60,
      align: 'center',
    },

    {
      title: '故障位激活',
      width: 80,
      search: false,
      align: 'center',
      key: 'faultBitActive',
      dataIndex: 'faultBitActive',
      valueType: 'select',
      valueEnum: {
        0: { text: 'OFF', status: 'Default', },
        1: { text: '用1个故障位启用', status: 'success', },
      },
    },
    {
      title: '故障电平',
      width: 80,
      search: false,
      align: 'center',
      key: 'faultLevel',
      dataIndex: 'faultLevel',
      valueType: 'select',
      valueEnum: {
        0: { text: '低电平', status: 'Default', },
        1: { text: '高电平', status: 'success', },
      },
    },
    {
      title: '故障位的位置',
      search: false,
      dataIndex: 'faultPos',
      width: 60,
      align: 'center',
    },
  ];

  const onFinish = async () => { 
    try {
      const result = driveRef.current.getFieldsValue();
      console.log(result, "---result---");
      if (encoderCreate) {
        result.id = (Math.random() * 1000000).toFixed(0);
        setDataSource([...dataSource, result]);
        await addEncoderConfig(result);
        message.success('添加成功');
      } else {
        if (result.id !== null && result.id !== undefined) {
          for (let i = 0; i < dataSource.length; i++) {
            if (dataSource[i].id === result.id) {
              Object.assign(dataSource[i], result);
            }
          }
          setDataSource(dataSource);
          await updateEncoderConfig(result);
          message.success('更新成功');
        }
      }
      actionRef.current?.reload();
      setVisible(false);
    } catch{}
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard title="编码器参数库" colSpan="100%" style={{ maxWidth: '100%', height: '100%' }}>
        <ProList<any>
          headerTitle="参数列表"
          search={{}}
          actionRef={actionRef}
          rowKey="id"
          // itemLayout="vertical"
          rowSelection={rowSelection}
          expandable={{
            expandedRowKeys,
            defaultExpandAllRows: true,
            onExpandedRowsChange: setExpandedRowKeys
          }}
          dataSource={dataSource}
          toolBarRender={(action, { selectedRows, selectedRowKeys }) => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setUploadVis(true);
              }}
            >
              导入
            </Button>,
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setValues({});
                setVisible(true);
                setEncoderCreate(true);
              }}
            >
              新建
            </Button>,
          ]}
          metas={{
            title: {
              dataIndex: 'encoderNum',
              search: false,
            },
            subTitle: {
              search: false,
              render: (text, row) => (
                <>
                  <Tag>{'编码器厂家: ' + row.encoderManufacturer}</Tag>
                  <Tag>{'编码器类型: ' + encoderTypeMap.get(row.encoderType)}</Tag>
                </>
              )
            },
            description: {
              search: false,
              render: (_, row) => {
                return <EncoderContent row={row} actionRef={actionRef}/>;
              },
            },
            content: {
              search: false,
            },
            actions: {
              render: (text, row) => [
                <a
                  href={row.html_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  key="modify"
                  onClick={async () => {
                    console.log(row, "---row---");
                    setEncoderCreate(false);
                    setVisible(true);
                    setValues({ ...row });
                  }}
                >
                  编辑
                </a>,
                <a
                  href={row.html_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  key="copy"
                  onClick={async () => {
                    let addone = {};
                    dataSource
                      .filter((item) => item.id == row.id)
                      .map((item) => {
                        addone = { ...item };
                      });
                    addone.id = (Math.random() * 1000000).toFixed(0);  
                    setDataSource([...dataSource, addone]);
                    delete addone.identification;
                    await addEncoderConfig(addone);
                    actionRef.current.reload();
                  }}
                >
                  复制
                </a>,
                <a
                  href={row.html_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  key="delete"
                  onClick={async () => {
                    setDataSource(dataSource.filter((item) => item.id !== row.id));
                    await delEncoderConfig(row);
                    actionRef.current.reload();
                  }}
                >
                  删除
                </a>,

              ]
            },

            encoderNum: {
              title: '编码器型号',
            },
          }}
          request={async (params = {}, sort, filter) => {
            console.log(params, sort, filter);
            const result = await getEncoderConfigByPage(params);
            console.log(result, '---result---');
            setDataSource(result.data.content);
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          pagination={{
            showSizeChanger: true,
          }}
        />
      </ProCard>
      <EncoderCommon
        visible={visible}
        title='编码器参数预览'
        disabled={false}
        values={values}
        ref={driveRef}
        initialValues={values}
        onCancel={() => {
          setVisible(false);
        }}
        onOk={onFinish}
      />
      <UploadFileSave
        visible={uploadVis}
        title='编码器上传参数预览'
        tableHeader={encoderColumns}
        errorStatus={false}
        ref={uploadRef}
        onChange={(file) => {
          formData.append('file', file);
        }}
        onCheck={() => { }}
        onCancel={() => {
          setUploadVis(false);
        }}
        onOk={async (tables, tableHeader) => {
          console.log(tables, "---tables---");
          
          console.log(uploadRef.current.fileList, '文件测试---');
          const result = await uploadEncoderExcel(formData);
          
          console.log(result, "---formData---");
          if (result != undefined && result != null) {
            setDataSource([...dataSource, result.data]);
          }
          // setDataSourceTwo(tables);
          actionRef.current.reload();
          setUploadVis(false);
        }}
      />
    </PageHeaderWrapper>
  );
};

export default EncoderConfigLib;